/*
* @(#) UnBlockingStack.java 2018年01月30日
*
* Copyright 2010 NetEase.com, Inc. All rights reserved.
*/
package com.leo.m1801.d30;

import com.leo.common.Node;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 写一个非阻塞的栈
 * @author xuexiaolei
 * @version 2018年01月30日
 */
public class UnBlockingStack<T> {
    public AtomicReference<Node<T>> top = new AtomicReference<Node<T>>();

    public T pop(){
        Node<T> tNode, newNode;
        do{
            tNode = top.get();
            newNode = tNode.next;
        }while (!top.compareAndSet(tNode, newNode));

        return tNode.value;
    }

    public void push(T t){
        Node<T> node = new Node<T>(t);
        Node<T> tNode;
        do{
            tNode = top.get();
            node.next = tNode;
        }while (!top.compareAndSet(tNode, node));
    }
}
